import router, { asyncRoutes } from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from './utils/get-page-title'

router.beforeEach(async(to, from, next) => {
  NProgress.start() // 开启进度条
  const whiteList = ['/login', '/404']
  // 网页标题
  document.title = getPageTitle(to.meta.title)
  const token = store.state.user.token
  if (token) {
    // console.log('有token')
    if (to.path === '/login') {
      // console.log('已登录,不能再去登录,直接去首页')
      next('/')
      NProgress.done()
    } else {
      // console.log('已登录,去其他页面,放行')
      if (!store.state.user.userInfo.userId) {
        const meuns = await store.dispatch('user/getUserInfo')
        // console.log(meuns, '用户页面级别的权限数据')
        // console.log(asyncRoutes, '动态页面路由')
        // 使用权限信息筛选出用户可以访问的动态路由
        const filterRoutes = asyncRoutes.filter(route => {
          return meuns.includes(route.children[0].name)
        })
        // console.log(filterRoutes)
        // x需要权限的信息,根据权限信息动态的添加路由,渲染左侧菜单
        filterRoutes.push({ path: '*', redirect: '/404', hidden: true })
        router.addRoutes(filterRoutes)
        store.commit('menus/setMenus', filterRoutes)
        // 404解决刷新出现白屏问题
        next({ ...to, replace: true })
      } else {
        next()
      }
    }
  } else {
    // console.log('没有token')
    // 判断是否有白名单
    if (whiteList.includes(to.path)) {
      // console.log('拥有白名单,放行')
      next()
    } else {
      // console.log('没有白名单,需要权限,请先登录')
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // console.log('页面跳转完成')
  NProgress.done() // 关闭进度条
})
